package 线程;

import com.sun.org.apache.xalan.internal.xsltc.compiler.util.VoidType;
import sun.misc.Unsafe;
import 注解.UserClassLoad;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author:谢君臣
 * @Date:2021/8/27-21:34
 * @version:1.0
 * @function:
 */
public class test1 {
    private static volatile int a = 0;
    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException, InterruptedException {
        ExecutorService service = Executors.newFixedThreadPool(10);
        service.submit(new Thread());
        service.execute(()->{});
        service.execute(new Thread());

        Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
        theUnsafe.setAccessible(true);
        Unsafe unsafe = (Unsafe) theUnsafe.get(null);
        System.out.println(unsafe);
        MyAtomicInteger temp = new MyAtomicInteger();
        for (int i = 0; i < 10; i++) {
            new Thread(()->temp.addAtomic()).start();
        }
        TimeUnit.SECONDS.sleep(1); // 保证10个线程运行完成
        System.out.println(temp.getValue());

    }

}
class MyAtomicInteger{
    static Unsafe unsafe;
    private volatile int value;
    private static long valueOffset;
    static {
        Field theUnsafe = null;
        try {
            theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
            theUnsafe.setAccessible(true);
            unsafe = (Unsafe) theUnsafe.get(null);
            valueOffset = unsafe.objectFieldOffset(MyAtomicInteger.class.getDeclaredField("value"));
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    public int getValue() {
        return value;
    }

    public void addAtomic(){
        while (true){
            int pre = this.value;
            int next = pre+1;
            if (unsafe.compareAndSwapInt(this,valueOffset,pre,next))
                break;
        }
    }

}

